<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { Toast } from "vant";
import { shallowRef } from "@vue/reactivity";
import AMapLoader from "@amap/amap-jsapi-loader";
let map = shallowRef<any>(null);
let AMap: any = null;
let infoWindow: any = null;
let city = ref('')
let latitude = ref('')
let longitude = ref('')
let loadingToast: any = null
const emits = defineEmits<{
  (e: "getData", data: object): void
}>()
const props = defineProps(['storeList'])
var openInfo = (name: string, address: string, longitude: string, latitude: string) => {
  //构建信息窗体中显示的内容
  var info = `<div class="flexCenter">
        <div class="maskerBox">
          <div>${name}</div>
          <div style="font-size: 13px;color:#999;margin-top:10px;">
            ${address}
          </div>
        </div>
        <a class="mapIcon" href="//uri.amap.com/marker?position=${longitude},${latitude}&name=${name}&src=mypage&coordinate=gaode&callnative=1">
          <img class="imgSize" src="/static/gaode.png" alt="加载失败">
        </a>
      </div>`

  infoWindow = new AMap.InfoWindow({
    offset: new AMap.Pixel(10, -30),
    content: info,
    anchor: 'info-top',
  });
  map.setCenter([longitude, latitude]);
  infoWindow.open(map, [longitude, latitude]);

}
watch(() => props.storeList, (newValue, oldValue) => {
  // map.clearMap();  // 清除地图覆盖物
  props.storeList.forEach((item: any, index: number) => {
    let marker = new AMap.Marker({
      map: map,
      position: [item.longitude, item.latitude],
      snippet: index,
      content: `<div>
      <div class="custom-content-marker" style="position:relative">
      <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png" style="width:34px">
      </div>
      <div style="position: absolute;left: 50%;top: 37%;transform: translate(-50%,-50%);color: #fff;font-size: 16px;">${index + 1}</div>
      </div>`,
      label: {
        direction: 'top'
      }
    });
    if (index == 0) {
      openInfo(item.name, item.address, item.longitude, item.latitude)
    }
    marker.on('click', function (e: any) {
      openInfo(item.name, item.address, item.longitude, item.latitude)
    })
  })

  map.add(props.storeList);
})

let initMap = () => {
  loadingToast = Toast.loading({
    duration: 0,
    message: '加载中',
    forbidClick: true
  })
  AMapLoader.load({
    key: "f1099289ce99e6a6129e0ea96d418587",
    version: "",
    plugins: ["AMap.Geolocation", "AMap.CitySearch", "AMap.PlaceSearch", "AMap.Marker"],
  }).then((e) => {
    AMap = e
    map = new AMap.Map("container", {
      zoomToAccuracy: true,
      resizeEnable: true,
      zoom: 13,
      center: [120.209385, 30.174631], //初始化地图中心点位置
      viewMode: "2D",
    });
    AMap.plugin('AMap.Geolocation', function () {
      let geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 3000,
        showMarker: true,
        panToLocation: true
      })
      map.addControl(geolocation)
      geolocation.getCurrentPosition()
      AMap.event.addListener(geolocation, 'complete', onComplete)
      AMap.event.addListener(geolocation, 'error', onError)
      function onComplete(data: any) {
        loadingToast.clear()
        longitude.value = data.position.lng
        latitude.value = data.position.lat
        city.value = data.addressComponent.city
        emits("getData", { city: city.value, longitude: longitude.value, latitude: latitude.value })
      }
      function onError(data: any) {
        // 定位出错
        loadingToast.clear()
        getLatLngLocation()
      }
    })
    function getLatLngLocation() {
      map.plugin("AMap.CitySearch", function () {
        let citySearch = new AMap.CitySearch();
        citySearch.getLocalCity(function (status: number, result: any) {
          city.value = result.city
          longitude.value = result.bounds.northeast.lng
          latitude.value = result.bounds.northeast.lat
          emits("getData", { city: city.value, longitude: longitude.value, latitude: latitude.value })
        });
      });
    }

  })
    .catch((e) => {
      console.log(e);
    });
};
onMounted(() => {
  initMap();
});
let clickData = (item: any) => {
  openInfo(item.name, item.address, item.longitude, item.latitude)
}
defineExpose({
  clickData
})
</script>

<template>
  <div id="container"></div>
</template>

<style scoped lang="less">
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 100%;
}

:deep(.amap-info-content) {
  box-shadow: 0 0 8px 0 #6b6b6b80;
  width: 300px;
  border-radius: 8px;
}

:deep(.flexCenter) {
  display: flex;
  justify-items: center;
  align-items: center;
}

:deep(.maskerBox) {
  width: 80%;
}

:deep(.maskerBox div) {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  color: #1677FF;
  font-size: 17px;
}

:deep(.mapIcon) {
  width: 24px;
  height: 24px;
}

:deep(.imgSize) {
  display: block;
  width: 100%;
  height: 100%;
}
</style>
